﻿using PIMS.WorkPlugin.ORM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.UI.WebControls;

namespace PIMS.WorkPlugin
{
    internal class DJGHelper
    {
        /// <summary>
        /// 60袋信息拆分
        /// </summary>
        /// <param name="bagInfo"></param>
        /// <returns></returns>
        public static List<string> HandleBagInfoArray(byte[] bagInfo, int onelenth=50)
        {
            List<string> list = new List<string>();
            for (int i = 0; i < bagInfo.Length; i += onelenth)
            {
                byte[] bag = new byte[onelenth];
                Array.Copy(bagInfo, i, bag, 0, bag.Length);
                string barcode = ByteArrayToString(bag).Replace("(","").Replace(")", "");

				string zero = "".PadRight(onelenth, '0'); //50个0
				if (!String.IsNullOrEmpty(barcode) && !barcode.StartsWith(zero))
                {
                    list.Add(barcode);
                }
            }
            return list;
        }

        /// <summary>
        /// ASCII字节数组转字符串，自动去掉0
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static string ByteArrayToString(byte[] b)
        {
            string result = "";
            int count = 0;
            for (int i = 0; i < b.Length; i++)
            {
                if (b[i] != 0)
                    count++;
                else
                    break;
            }
            if (count == 0) return "";
            byte[] b2 = new byte[count];
            Array.Copy(b, b2, count);
            result = Encoding.ASCII.GetString(b2);
            return result;
        }

        /// <summary>
        /// 调用存储过程生成唯一流水号
        /// </summary>
        /// <returns></returns>
        public static string GeneralSerialNum(int id)
        {
            Dictionary<string, object> intParams = new Dictionary<string, object>()
            {
                { "Serialid",id}
            };
            Dictionary<string, object> outParams = new Dictionary<string, object>()
            {
                { "returnValue",""}
            };
            SqlSugarHelper.ExecuteProcedure("sp_GenSerialNum", intParams, outParams);
            if (String.IsNullOrEmpty(outParams["returnValue"].ToString()))
            {
                throw new Exception("sp_GenSerialNum Error!");
            }
            return outParams["returnValue"].ToString();
        }

        public static string GenaralBatchSerialNum(string sLine)
        {
            Dictionary<string, object> intParams = new Dictionary<string, object>()
            {
                { "Line",sLine}
            };
            Dictionary<string, object> outParams = new Dictionary<string, object>()
            {
                { "returnValue",""}
            };
            SqlSugarHelper.ExecuteProcedure("sp_CreateBatchNo", intParams, outParams);
            if (String.IsNullOrEmpty(outParams["returnValue"].ToString()))
            {
                throw new Exception("sp_CreateBatchNo Error!");
            }
            return outParams["returnValue"].ToString();
        }

        /// <summary>
        /// 检查60袋的型号代码是否一致
        /// X2P321092800001,D26,YX-B-26-201011 (34位)
        /// LH1PS0122101400001,051,LH-A-09-20221019 (39位)
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static bool CheckProductType(List<string> list,out string errMsg)
        {
            errMsg = "";
            try
            {
                string type = "";
                for (int i = 0; i < list.Count; i++)
                {
                    if(!list[i].Contains(","))
                    {
                        errMsg = string.Format("袋{0}二维码{1}错误:不含逗号！",i+1, list[i]);
                        return false;
                    }
                    if (i == 0)
                    {
                        type = list[i].Split(',')[1];
                    }
                    else
                    {
                        if (type != list[i].Split(',')[1])
                        {
                            errMsg= "首袋类型:" + type + " 错误类型:" + list[i].Split(',')[1];
                            return false;
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                errMsg = "检测袋类型出错：" + ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 正则表达式验证中文字符
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static bool JustChinese(string text = "天下英雄abc")
        {
            for (int i = 0; i < text.Length; i++)
            {
                //判断汉字的Unicode编码范围
                if (Regex.IsMatch(text[i].ToString(), @"[\u4e00-\u9fbb]"))
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 字符串转Unicode码
        /// 以\u开头
        /// </summary>
        /// <returns>The to unicode.</returns>
        /// <param name="value">Value.</param>
        public static string StringToUnicode(string value)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(value);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i += 2)
            {
                // 取两个字符，每个字符都是右对齐。
                stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
            }
            return stringBuilder.ToString();
        }

        /// <summary>
        /// 统计批次列表中，哪个批次最多，最多的是batchCount[0].Value
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static List<CountInfo> CountList(List<string> list)
        {
            List<CountInfo> info = new List<CountInfo>();

            // 集合 dic 用于存放统计结果
            Dictionary<string, CountInfo> dic = new Dictionary<string, CountInfo>();
            //开始统计每个元素重复次数
            foreach (string v in list)
            {
                if (dic.ContainsKey(v))
                {
                    // 数组元素再次，出现次数增加 1
                    dic[v].RepeatNum += 1;
                }
                else
                {
                    // 数组元素首次出现，向集合中添加一个新项
                    // 注意 ItemInfo类构造函数中，已经将重复
                    // 次数设置为 1
                    dic.Add(v, new CountInfo(v));
                }
            }
            foreach (CountInfo count in dic.Values)
            {
                info.Add(count);
            }
            List<CountInfo> sortInfo = info.OrderByDescending(o => o.RepeatNum).ToList();//降序排序
            return sortInfo;
        }
    }

    public class CountInfo
    {
        /// <summary>
        /// ItemInfo 类记录数组元素重复次数
        /// </summary>
        /// <param name="value">数组元素值</param>
        public CountInfo(string value)
        {
            Value = value;
            RepeatNum = 1;
        }
        /// <summary>
        /// 数组元素的值
        /// </summary>
        public string Value { get; set; }
        /// <summary>
        /// 数组元素重复的次数
        /// </summary>
        public int RepeatNum { get; set; }
    }
}
